﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.Web.Security;
using Newtonsoft.Json.Linq;

namespace IReklamo.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult FacebookLogin(string accessToken, string userId, string expiresIn)
        {
            var client = new WebClient();
            string JsonResult = client.DownloadString(string.Concat("https://graph.facebook.com/me?access_token=", accessToken));
            var jsonUserInfo = JObject.Parse(JsonResult);
            string name = jsonUserInfo.Value<string>("name");
            string email = jsonUserInfo.Value<string>("email");
            string locale = jsonUserInfo.Value<string>("locale");
            string facebook_userID = jsonUserInfo.Value<string>("id");

            var authCookie = FormsAuthentication.GetAuthCookie(userId.ToString(), true);
            var ticket = FormsAuthentication.Decrypt(authCookie.Value);
            DateTime expiration = ticket.IssueDate.AddSeconds(Convert.ToDouble(expiresIn));// we want to change the expiration of our forms authentication cookie to match the token expiration date, but you can also use your own expiration
            var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, expiration, ticket.IsPersistent, name);

            authCookie.Value = FormsAuthentication.Encrypt(newTicket);// encrypt the cookie again
            Response.Cookies.Add(authCookie);// manually set it (instead of calling FormsAuthentication.SetAuthCookie)

            return RedirectToAction("Index", "Home");
        }

        public PartialViewResult LogoutPartialView()
        {
            return PartialView();
        }

        public ActionResult Logoff()
        {
            var x = HttpContext.User.Identity.Name;
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }
}
